import os 
import wave
import contextlib    # 获取音频的时长   上下文  管理机制
from datetime import datetime, timedelta
import shutil   # 复制音频文件
import re       # 查找正则

# 将 xxxxx_.wav 文件名字 转换为 字符-xx-xx xx:xx:xx
def format_string(input_str):
    # 去掉后缀 "_test"
    cleaned_str = input_str.split("_")[0]
    
    # 提取日期和时间部分
    month = cleaned_str[:2]
    day = cleaned_str[2:4]
    hour = cleaned_str[4:6]
    minute = cleaned_str[6:8]
    second = cleaned_str[8:10]
    
    # 拼接成目标格式
    formatted = f"-{month}-{day} {hour}:{minute}:{second}"
    return formatted


# 获取音频文件的时长
def get_wav_duration(file_path):
    with contextlib.closing(wave.open(file_path, 'r')) as wav_file:
        frames = wav_file.getnframes()
        rate = wav_file.getframerate()
        duration = frames / float(rate)
    return duration


# 将获取的音频时长加到 开始时间上
def add_seconds_to_time(base_time_str, seconds):
    # 将字符串解析为 datetime 对象
    base_time = datetime.strptime(base_time_str, "-%m-%d %H:%M:%S")
    
    # 增加秒数
    new_time = base_time + timedelta(seconds=seconds)
    
    # 格式化回字符串
    return new_time.strftime("-%m-%d %H:%M:%S")


# 获取气压值.log 里面的年份   返回年份字符串
def return_year(input_file):
    # 提取年份的正则表达式
    pattern = r"\[(\d{4})-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\]"
    # 打开文件并读取内容
    with open(input_file, 'r') as file:
        for line in file:
            match = re.search(pattern, line)  # 搜索年份
            if match:
                first_year = match.group(1)  # 提取第一个年份
                return first_year             # 找到第一个年份后立即退出            


# 判断时间行 并且写入文件  start_time, end_time 是字符串格式 
def extract_log(input_file, output_file, start_time, end_time):
    matching_lines = []  # 用于存储符合条件的行
    with open(input_file, 'r') as infile:
        # # 读取第一行的内容
        # first_line = infile.readline()
        # # 提取时间部分
        # if first_line.startswith('['):  # 判断是否是时间行
        #     timestamp_str = first_line.split(']')[0].strip('[')  # 提取时间字符串
        #     timestamp = datetime.strptime(timestamp_str, "%Y-%m-%d %H:%M:%S")
        #     year = timestamp.year
        #     end_time = str(year) + str(end_time)
        #     start_time = str(year) + str(start_time)
        #     end_time = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
        #     start_time = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")

        year = return_year(input_file)
        end_time = str(year) + str(end_time)
        start_time = str(year) + str(start_time)
        end_time = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
        start_time = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")


        for line in infile:
            # 提取时间部分
            if line.startswith('['):  # 判断是否是时间行
                timestamp_str = line.split(']')[0].strip('[')  # 提取时间字符串
                try:
                    timestamp = datetime.strptime(timestamp_str, "%Y-%m-%d %H:%M:%S")

                    # 检查时间是否在范围内
                    if start_time <= timestamp <= end_time:
                        matching_lines.append(line)
                except:
                    print(input_file, "处理.log文件出现问题.....")
                    continue

    with open(output_file, 'w') as outfile:
        outfile.writelines(matching_lines)

# 是否能够找到文件夹
path_file = "E:\data\鼾声多模态\止鼾枕体验数据"    # 所有文件的根目录
path_file_save = "E:\data\鼾声多模态\止鼾枕清洗后的数据"      # 文件保存到新的文件夹下

if os.path.exists(path_file):
    print("存在该目录....")

# 0. 获取该文件夹下的所有列表
list_all_file = os.listdir(path_file)
print("输出所有的文件夹: ",list_all_file)

save_file = ['0102', '0103', '0104', '0105', '0108', '0110', '0111', '0112', '0115', '0116', '0117', 
             '0118', '0119', '0122', '0124', '0125', '0126', '0129', '0130', '0131', '0201', '0307', '0310', 
             '0311', '0313', '0314', '0321']

# 1. 对其中列表进行处理
for i in list_all_file:
    if i in save_file :   # 这是已经保存的文件
        continue
    list_file_index = os.listdir(os.path.join(path_file, i))
    # print(list_file_index) 
    
    for j in list_file_index:
        # 判断是文件 还是文件夹
        is_file = os.path.join(path_file, i, j)
        if os.path.isfile(is_file):
            continue   # 是文件则进行下一次循环
        # 2. 查询是否有  XXXXX_test.wav 文件
        list_file = os.listdir(os.path.join(path_file, i, j))  
        object_wav = [x for x in list_file if x.endswith("_test.wav")]   # 找到xxx_test.wav的文件
        print(i, "文件夹下的", object_wav)   # 可能有多个 wav文件
        for p in object_wav:
            # 格式化wav文件名称
            start_content = format_string(p)
            # print(start_content)
            # 获取音频时长
            time_wav = get_wav_duration(os.path.join(path_file, i, j, p))
            # print(time_wav)
            end_content =  add_seconds_to_time(start_content, time_wav)
            # print(end_content)
        # 3. 截取止鼾枕的气压值
            if "pillow_log.log" in list_file: # 是否有 pillow_log.log 文件 
                # 创建要保存的文件
                if not os.path.exists(os.path.join(path_file_save, i, j)):
                    os.makedirs(os.path.join(path_file_save, i, j))     # 递归创建文件夹
                # 读取 pillow_log.log 文件
                print(i, "文件夹下的", "正在截取枕头气压值........")
                extract_log(os.path.join(path_file, i, j, "pillow_log.log"), 
                            os.path.join(path_file_save, i, j, p.split("_")[0]+".log"), start_content, end_content)
        # 4. 保存 音频文件和气压值 到单独的文件下
                print(i, "文件夹下的", "正在移动音频文件到目标文件夹下.......")
                # 源文件和目标路径
                source_file = os.path.join(path_file, i, j, p)
                destination_file = os.path.join(path_file_save, i, j, p)

                # 复制文件
                shutil.copy(source_file, destination_file)
                print(i, "文件夹下的", "音频文件已经复制完成.......")
            else:
                # 不存在音频文件 则退出
                break
    # break
